import 'package:base_lib/common/bus/ibus.dart';
import 'package:base_lib/dictionary/dictionary_http.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/repository/http.dart';
import 'package:base_lib/router/routers.dart';
import 'package:base_lib/utils/shared_preference_util.dart';
import 'package:flutter/cupertino.dart';
import 'common/bus/bus.dart';
import 'config.dart';
import 'router/page_builder.dart';

class App {
  static String latitude = '30.53972816467285';

  static String longitude = '104.05217742919922';

  ///抓包地址
  static String httpProxy = '';

  ///编译环境
  static final bool inProduction =
      const bool.fromEnvironment("dart.vm.product");

  ///数据默认缓存时长
  static num dataCachePeriod = 1000 * 60 * 60 * 24 * 30;

  /// 对应h5的远程地址
  static const String PATH_REMOTE_H5 = "https://apph5.100cbc.com";

  ///    MaterialApp(
  ///     navigatorKey: navigatorKey,
  ///     )
  static final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

  static void initializer(
      List<IComponent> components, String loginPage, String mainPage,
      {fileBaseUrl = Config.fileBaseUrl,
      dictionaryBaseUrl = Config.loginBaseUrl,
      dataCachePeriod,
      logTag}) async {
    await SPUtil.getInstance();

    DictionaryHttp.createHttpProxy(mBaseUrl: dictionaryBaseUrl);

    FileHttp.createHttpProxy(mBaseUrl: fileBaseUrl);

    App.dataCachePeriod = dataCachePeriod ?? App.dataCachePeriod;
    components.forEach((module) {
      //各个组件的初始化
      module.doComponentInitConfig();

      //注册各个组件的页面
      var pages = module.getPages();
      Routers.init(pages);

      //注册各个组件的公共服务
      var publicEvents = module.gePublicEvents();
      publicEvents.forEach((publicEvent) {
        EventBus.instance.register(publicEvent.event, publicEvent.iSubscriber,
            componentName: publicEvent.componentName, type: EventType.get);
      });
    });
    Routers.initLoginPage(loginPage);
    Routers.initMainPage(mainPage);
  }
}

abstract class IComponent {
  String get componentName => getComponentName();

  ///获取ComponentName
  getComponentName();

  ///做一些组件初始化的工作
  void doComponentInitConfig();

  ///对外提供的路由页面
  List<PageBuilder> getPages();

  ///对外提供的可以被响应的event事件
  ///此处注册测事件都是[EventType.get],可以主动 [EventBus.instance#get()] 调用
  List<EventBuilder> gePublicEvents();
}
